package com.example.opengltest1;

import android.opengl.GLES20;
import android.opengl.GLSurfaceView;
import android.opengl.Matrix;
import android.os.SystemClock;

import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;

public class OneGlRenderer implements GLSurfaceView.Renderer {

    private Triangle mTriangle;
    private Square mSquare;

    @Override
    public void onSurfaceCreated(GL10 gl10, EGLConfig eglConfig) {
        // 设置背景颜色，red,green,blue,alpha，0~1.0f|0~255
        GLES20.glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
        // 初始化triangle
        mTriangle = new Triangle();
        // 初始化square
        mSquare = new Square();
    }

    private final float[] mMVPMatrix = new float[16];
    private final float[] mProjectionMatrix = new float[16];
    private final float[] mViewMatrix = new float[16];

    @Override
    public void onSurfaceChanged(GL10 gl10, int i, int i1) {
        // 设置图像显示窗口大小
        GLES20.glViewport(0, 0, i/2, i1/2);

        // 绘制正交投影矩阵
        // Matrix.orthoM();

        float ratio = (float) i / i1;
        // 绘制透视投影矩阵，保持图像不变形，
        Matrix.frustumM(mProjectionMatrix, 0, -ratio, ratio, -1, 1, 3, 7);
    }

    private float[] mRotationMatrix = new float[16];

    // 两种被调用的模式设定：
    // 1、GLSurfaceView.RENDERMODE_WHEN_DIRTY    按需渲染，调用GLSurfaceView.requestRender()
    // 2、GLSufaceView.RENDERMODE_CONTINUOUSLY   连续渲染，GL线程会每隔一段时间自动刷新渲染【默认】
    @Override
    public void onDrawFrame(GL10 gl10) {
        float[] scratch = new float[16];

        // 重绘背景颜色
        GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT);
        // 绘制相机视图矩阵，确定相机模型，也便于理解up向量
        Matrix.setLookAtM(mViewMatrix, 0, 0, 0, -3, 0f,0f, 0f, 0f, 1.0f, 0.0f);
        // 相乘得到投影和相机视图矩阵
        Matrix.multiplyMM(mMVPMatrix, 0, mProjectionMatrix, 0, mViewMatrix, 0);

//        mTriangle.draw(mMVPMatrix);   // 投影和相机视图矩阵

        // 创建一个旋转矩阵
        long time = SystemClock.uptimeMillis() % 4000L;
        float angle = 0.090f * ((int) time);
        // 绘制旋转矩阵
        Matrix.setRotateM(mRotationMatrix, 0, angle, 0, 0, -1.0f);
        // 相乘得到投影、相机视图和旋转矩阵
        Matrix.multiplyMM(scratch, 0, mMVPMatrix, 0, mRotationMatrix, 0);

        mTriangle.draw(scratch);
    }

    // 执行着色器代码【共有静态】
    public static int loadShader(int type, String shaderCode){

        // 创造顶点着色器类型(GLES20.GL_VERTEX_SHADER)
        // 或者是片段着色器类型 (GLES20.GL_FRAGMENT_SHADER)
        int shader = GLES20.glCreateShader(type);
        // 添加着色器代码
        GLES20.glShaderSource(shader, shaderCode);
        // 编译着色器代码
        GLES20.glCompileShader(shader);
        return shader;
    }
}
